package com.insurance.common.utils;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import org.apache.commons.lang.StringUtils;
import org.springframework.util.DigestUtils;

import java.util.Map;

/**
 * 接口加密工具类
 *
 * @author Style
 * @version 1.0
 * @date 2021/1/27
 **/
public class SignUtil {

    /**
     * md5加密
     *
     * @param encryptStr 加密字符串
     * @return
     */
    public static String md5Digest(String encryptStr){
        return DigestUtils.md5DigestAsHex((encryptStr).getBytes());
    }

    /**
     * 签名
     *
     * @param encryptStr 加密字符串
     * @return
     */
    public static String sign(String encryptStr){
        return md5Digest(md5Digest(encryptStr));
    }

    /**
     * 验签
     *
     * @param originalStr 明文
     * @param signStr 密文
     * @return
     */
    public static boolean verification(String originalStr, String signStr){
        if(StringUtils.isBlank(originalStr) || StringUtils.isBlank(signStr)){
            return false;
        }
        System.out.println(sign(originalStr));
        return signStr.equals(sign(originalStr));
    }

    /**
     * ascii码排序(小到大)
     *
     * @param paramMap 参数
     * @return
     */
    public static String asciiSort(Map<String, Object> paramMap){
        try {
            if(paramMap == null){
                return new JSONObject().toString();
            }
            String sign = JSONObject.toJSONString(paramMap, SerializerFeature.MapSortField);
            return sign;
        } catch (Exception e) {
            System.out.println("【签名失败】");
            e.printStackTrace();
            return new JSONObject().toString();
        }
    }

    /**
     * ascii码签名(两次MD5)
     *
     * @param paramMap 签名参数
     * @return
     */
    public static String asciiSign(Map<String, Object> paramMap){
        String sign = asciiSort(paramMap);
        System.out.println(sign);
        return sign(sign);
    }

    /**
     * 校验ascii码签名排序
     *
     * @param paramMap
     * @param signStr
     * @return
     */
    public static boolean validateAsciiSign(Map<String, Object> paramMap, String signStr){
        if(paramMap == null  || StringUtils.isBlank(signStr)){
            return false;
        }
        String sign = asciiSign(paramMap);
        System.out.println(sign);
        return sign.equals(signStr);
    }

    public static void main(String[] args) {
        String sign = sign("18611291899168c9e00de35370fbbb5768aaa9c5769123123");
        System.out.println(sign);
    }


}
